﻿#include "codebrowser.h"

#include <QTextBlock>

CodeBrowser::CodeBrowser(QWidget *parent)
    : QTextBrowser(parent)
    , m_step(0)
    , m_stepCount(0)
{
    setTextInteractionFlags(Qt::TextSelectableByMouse);
    setLineWrapMode(QTextBrowser::NoWrap);
    connect(this, &QTextBrowser::cursorPositionChanged, [=]()
    {
        //选中当前行
        QList<QTextEdit::ExtraSelection> extraSelection;
        QTextEdit::ExtraSelection selection;
        QColor lineColor = QColor(Qt::gray).lighter(120);
        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        //将刚设置的 selection追加到链表当中
        extraSelection.append(selection);
        setExtraSelections(extraSelection);
        setStep(selection.cursor.block().firstLineNumber());
    });
}

void CodeBrowser::setCode(const QString &text)
{
    clear();
    setPlainText(text);
    m_stepCount = document()->lineCount();
    emit loadFinished();
}

QString CodeBrowser::code() const
{
    return toPlainText();
}

void CodeBrowser::setStep(const int step)
{
    if(m_step != step)
    {
        m_step = step;
        QTextBlock block = document()->findBlockByLineNumber(step);
        QTextCursor cursor = textCursor();
        cursor.setPosition(block.position());
        setTextCursor(cursor);
        ensureCursorVisible();
        emit stepChanged(step);
    }
}

int CodeBrowser::step() const
{
    return m_step;
}

int CodeBrowser::stepCount() const
{
    return m_stepCount;
}

void CodeBrowser::setStepCount(const int count)
{
    m_stepCount = count;
}
